package org.yun.seckill;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.yun.biz.model.Order;
import org.yun.constants.Constant;
import org.yun.util.RedisUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Map;

import static org.yun.constants.RedisConstant.*;
import static org.yun.util.CommonUtil.checkActivity;
import static org.yun.util.RedisUtil.SEC_KILL_SCRIPT;


/**
 * @ProjectName: no-concurrent
 * @ClassName: NormalStrategy
 * @Description: 限流+防重复+redis扣库存+同步mysql
 * @Author: liyunfeng31
 * @Date: 2020/10/4 23:22
 */
@SuppressWarnings("UnstableApiUsage")
@Component
public class NormalStrategy implements SeckillStrategy {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RabbitTemplate rabbitTemplate;

    RateLimiter limiter = RateLimiter.create(200.0);


    @Override
    public int secKill(Long userId, Long skuId, Long activityId, Integer num, String ip) {
        if(!limiter.tryAcquire()){ return 0; }
        Map<Object, Object> activity = redisUtil.hmget(ACTIVITY_SKU + activityId + "_" + skuId);
        checkActivity(activity,false);

        String skuAct = skuId +":"+ activityId;
        String stockKey = STOCK + skuAct;
        String userIdsKey = USER_IDS + skuAct;

        Long result = redisUtil.executeScript(SEC_KILL_SCRIPT, Arrays.asList(stockKey, userIdsKey), userId.toString(), num.toString());
        if(!Constant.SUCCESS.equals(result)){ return 0; }
        Order order = Order.initOrder(userId,skuId,activityId, BigDecimal.TEN);
       // rabbitTemplate.convertAndSend("topicExchange", "topic.record", order);
        return 1;
    }

}
